﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace RedHouse.AdminControl.UserControls.Setting
{
    public partial class EmailSetting : System.Web.UI.UserControl
    {
        public string Message { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            btnSave.Click += new EventHandler(btnSave_Click);
            Initialize();
           
        }

        private void Initialize()
        {
            SuccessPanel.Visible = false;
            ErrorPanel.Visible = false;
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = @"Web.config";
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            ConfigurationSection section = config.Sections["EmailSettings"];
            if (section != null)
            {
                txtMailServer.Text = section.ElementInformation.Properties["MailServer"].Value.ToString();
                txtPort.Text = section.ElementInformation.Properties["Port"].Value.ToString();
                txtEmail.Text = section.ElementInformation.Properties["EmailAddress"].Value.ToString();
                txtPassword.Text = section.ElementInformation.Properties["Password"].Value.ToString();
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                RedHouse.Data.Common.EmailSetting configData = new RedHouse.Data.Common.EmailSetting()
                {
                    MailServer = txtMailServer.Text,
                    Port = txtPort.Text,
                    EmailAddress = txtEmail.Text,
                    Password = txtPassword.Text
                };
                ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                fileMap.ExeConfigFilename = @"Web.config";
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                config.Sections.Remove("EmailSettings");
                config.Sections.Add("EmailSettings", configData);
                Message = "Email settings saved successfully!";
                SuccessPanel.Visible = true;
                ErrorPanel.Visible = false;    
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                SuccessPanel.Visible = false;
                ErrorPanel.Visible = true;
            }

        }
    }
}